<?php
/**
 * Initialise the roles module
 *
 * @package modules
 * @copyright (C) 2002-2007 The Digital Development Foundation
 * @license GPL {@link http://www.gnu.org/licenses/gpl.html}
 * @link http://www.xaraya.com
 *
 * @subpackage Roles module
 * @link http://xaraya.com/index.php/release/27.html
 * @author Jan Schrage, John Cox, Gregor Rothfuss
 */

/**
 * Initialise the roles module
 *
 * @access public
 * @param none $
 * @return bool
 * @throws DATABASE_ERROR
 */
function roles_init()
{
    // Get database setup
    $dbconn =& xarDBGetConn();
    $tables =& xarDBGetTables();

    $sitePrefix = xarDBGetSiteTablePrefix();
    $tables['roles'] = $sitePrefix . '_roles';
    $tables['rolemembers'] = $sitePrefix . '_rolemembers';
    // prefix_roles
    /**
     * CREATE TABLE xar_roles (
     *    xar_uid int(11) NOT NULL auto_increment,
     *    xar_name varchar(100) NOT NULL default '',
     *    xar_type int(11) NOT NULL default '0',
     *    xar_users int(11) NOT NULL default '0',
     *    xar_uname varchar(100) NOT NULL default '',
     *    xar_email varchar(100) NOT NULL default '',
     *    xar_pass varchar(100) NOT NULL default '',
     *    xar_date_reg datetime NOT NULL default '0000-00-00 00:00:00',
     *    xar_valcode varchar(35) NOT NULL default '',
     *    xar_state int(3) NOT NULL default '0',
     *    xar_auth_module varchar(100) NOT NULL default '',
     *    PRIMARY KEY  (xar_uid)
     * )
     */

    $query = xarDBCreateTable($tables['roles'],
        array('xar_uid' => array('type' => 'integer',
                'null' => false,
                'default' => '0',
                'increment' => true,
                'primary_key' => true),
            'xar_name' => array('type' => 'varchar',
                'size' => 255,
                'null' => false,
                'default' => ''),
            'xar_type' => array('type' => 'integer',
                'null' => false,
                'default' => '0'),
            'xar_users' => array('type' => 'integer',
                'null' => false,
                'default' => '0'),
            'xar_uname' => array('type' => 'varchar',
                'size' => 255,
                'null' => false,
                'default' => ''),
            'xar_email' => array('type' => 'varchar',
                'size' => 255,
                'null' => false,
                'default' => ''),
            'xar_pass' => array('type' => 'varchar',
                'size' => 100,
                'null' => false,
                'default' => ''),
            'xar_date_reg' => array('type' => 'varchar',
                'size' => 100,
                'null' => false,
                'default' => '0000-00-00 00:00:00'),
            'xar_valcode' => array('type' => 'varchar',
                'size' => 35,
                'null' => false,
                'default' => ''),
            'xar_state' => array('type' => 'integer',
                'null' => false,
                'default' => '3'),
            'xar_auth_module' => array('type' => 'varchar',
                'size' => 100,
                'null' => false,
                'default' => '')));

    if (!$dbconn->Execute($query)) return;

    // role type is used in all group look-ups (e.g. security checks)
    $index = array('name' => 'i_' . $sitePrefix . '_roles_type',
        'fields' => array('xar_type')
        );
    $query = xarDBCreateIndex($tables['roles'], $index);
    $result = &$dbconn->Execute($query);
    if (!$result) return;
    // username must be unique (for login) + don't allow groupname to be the same either
    $index = array('name' => 'i_' . $sitePrefix . '_roles_uname',
        'fields' => array('xar_uname'),
        'unique' => true
        );
    $query = xarDBCreateIndex($tables['roles'], $index);
    $result = &$dbconn->Execute($query);
    if (!$result) return;
    // allow identical display names here
    $index = array('name' => 'i_' . $sitePrefix . '_roles_name',
        'fields' => array('xar_name'),
        'unique' => false
        );
    $query = xarDBCreateIndex($tables['roles'], $index);
    $result = &$dbconn->Execute($query);
    if (!$result) return;
    // allow identical e-mail here (???) + is empty for groups !
    $index = array('name' => 'i_' . $sitePrefix . '_roles_email',
        'fields' => array('xar_email'),
        'unique' => false
        );
    $query = xarDBCreateIndex($tables['roles'], $index);
    $result = &$dbconn->Execute($query);
    if (!$result) return;
    // role state is used in many user lookups
    $index = array('name' => 'i_' . $sitePrefix . '_roles_state',
        'fields' => array('xar_state'),
        'unique' => false
        );
    $query = xarDBCreateIndex($tables['roles'], $index);
    $result = &$dbconn->Execute($query);
    if (!$result) return;

    // prefix_rolemembers
    /**
     * CREATE TABLE xar_rolemembers (
     *    xar_uid int(11) NOT NULL default '0',
     *    xar_parentid int(11) NOT NULL default '0'
     * )
     */

    $query = xarDBCreateTable($tables['rolemembers'],
        array('xar_uid' => array('type' => 'integer',
                'null'  => false,
                'default' => '0'),
            'xar_parentid' => array('type' => 'integer',
                'null' => false,
                'default' => '0')));
    if (!$dbconn->Execute($query)) return;

    $index = array('name' => 'i_' . $sitePrefix . '_rolememb_id',
        'fields' => array('xar_uid','xar_parentid'),
        'unique' => true);
    $query = xarDBCreateIndex($tables['rolemembers'], $index);
    if (!$dbconn->Execute($query)) return;

    $index = array('name' => 'i_' . $sitePrefix . '_rolememb_parentid',
        'fields' => array('xar_parentid'),
        'unique' => false);
    $query = xarDBCreateIndex($tables['rolemembers'], $index);
    if (!$dbconn->Execute($query)) return;
    //Database Initialisation successful

    return true;
}

function roles_activate()
{
    //TODO: this stuff is happening here because at install blocks is not yet installed

    // only go through this once
# --------------------------------------------------------
#
# Create some modvars
#
    //TODO: improve on this hardwiring
    xarModSetVar('roles', 'defaultauthmodule', xarModGetIDFromName('authsystem'), 'integer'); //Setting a default
    xarModSetVar('roles', 'defaultregmodule', '', 'string');
    if (xarModGetVar('roles','itemsperpage')) return true;
    xarModSetVar('roles', 'rolesdisplay', 'tabbed', 'string');
    xarModSetVar('roles', 'locale', '', 'string');
    xarModSetVar('roles', 'userhome', '', 'string');
    xarModSetVar('roles', 'userlastlogin', '', 'string');
    xarModSetVar('roles', 'primaryparent', '', 'string');
    xarModSetVar('roles', 'usertimezone', '', 'string');
    xarModSetVar('roles', 'setuserhome',false, 'boolean');
    xarModSetVar('roles', 'setprimaryparent', false, 'boolean');
    xarModSetVar('roles', 'setpasswordupdate',false, 'boolean');
    xarModSetVar('roles', 'setuserlastlogin',false, 'boolean');
    xarModSetVar('roles', 'setusertimezone',false, 'boolean');
    xarModSetVar('roles', 'defaultgroup', 'Users', 'string');
    xarModSetVar('roles', 'displayrolelist', false, 'boolean');
    xarModSetVar('roles', 'usereditaccount', true, 'boolean');
    xarModSetVar('roles', 'allowuserhomeedit', false, 'boolean');
    xarModSetVar('roles', 'loginredirect', true, 'boolean');
    xarModSetVar('roles', 'allowexternalurl', false, 'boolean');
    xarModSetVar('roles', 'usersendemails', false, 'boolean');
    xarModSetVar('roles', 'requirevalidation', true, 'boolean');

    $emails = 'none@none.com
president@whitehouse.gov';
    $disallowedemails = serialize($emails);
    xarModSetVar('roles', 'disallowedemails', $disallowedemails, 'array');

    $lockdata = array('roles' => array( array('uid' => 4,
                                              'name' => 'Administrators',
                                              'notify' => TRUE)),
                                  'message' => '',
                                  'locked' => 0,
                                  'notifymsg' => '',
                                  'killactive' => FALSE);
    xarModSetVar('roles', 'lockdata', serialize($lockdata), 'array');

    xarModSetVar('roles', 'itemsperpage', 20, 'integer');
    // save the uids of the default roles for later
    $role = xarFindRole('Everybody');
    xarModSetVar('roles', 'everybody', $role->getID(), 'integer');
    $role = xarFindRole('Anonymous');
    xarConfigSetVar('Site.User.AnonymousUID', $role->getID(), 'integer');
    // set the current session information to the right anonymous uid
    xarSession_setUserInfo($role->getID(), 0);
    $role = xarFindRole('Admin');
    if (!isset($role)) {
      $role=xarUFindRole('Admin');
    }
    xarModSetVar('roles', 'admin', $role->getID(), 'integer');

    return true;
}

/**
 * Upgrade the roles module from an old version
 *
 * @access public
 * @param string oldVersion $
 * @return bool true on success
 * @throws DATABASE_ERROR
 */
function roles_upgrade($oldVersion)
{
    // Upgrade dependent on old version number
    switch ($oldVersion) {
        case '1.01':
            break;
        case '1.1.0':

            // is there an authentication module?
            $regid = xarModGetIDFromName('authsystem');

            if (isset($regid)) {

                // upgrade and activate the authsystem module - should be done before roles upgrade
                //if (!xarModAPIFunc('modules', 'admin', 'upgrade', array('regid' => $regid))) return;
                    // Activate the module
                //if (!xarModAPIFunc('modules', 'admin', 'activate', array('regid' => $regid))) return;

                // remove the login block type and block from roles
                $result = xarModAPIfunc('blocks', 'admin', 'delete_type', array('module' => 'roles', 'type' => 'login'));
                // delete the old roles modvars
                xarModDelVar('roles', 'allowregistration');
                xarModDelVar('roles', 'rolesperpage');
                xarModDelVar('roles', 'uniqueemail'); //this really should be in roles to avoid non core dependencies
                xarModDelVar('roles', 'askwelcomeemail');
                xarModDelVar('roles', 'askvalidationemail');
                xarModDelVar('roles', 'askdeactivationemail');
                xarModDelVar('roles', 'askpendingemail');
                xarModDelVar('roles', 'askpasswordemail');
                xarModDelVar('roles', 'lockouttime');
                xarModDelVar('roles', 'lockouttries');
                xarModDelVar('roles', 'minage');
                xarModDelVar('roles', 'disallowednames');
                xarModDelVar('roles', 'disallowedemails');
                xarModDelVar('roles', 'disallowedips');

                // create one new roles modvar
                xarModSetVar('roles', 'defaultauthmodule', xarModGetIDFromName('authsystem'), 'integer');
             } else {
//                $msg = xarML('I could not load the authentication module. Please make it available and try again');
//                xarErrorSet(XAR_USER_EXCEPTION, 'MODULE_FILE_NOT_EXIST', new DefaultUserException($msg));
//                return;
                die(xarML('I could not detect and load an authentication module (default is Authsystem). Please make an authentication module available and try again'));
            }
            xarModSetVar('roles', 'locale', '', 'string');
            xarModSetVar('roles', 'userhome', '', 'string');
            xarModSetVar('roles', 'userlastlogin', '', 'string');
            xarModSetVar('roles', 'primaryparent', '', 'string');
            xarModSetVar('roles', 'usertimezone', '', 'string');
            xarModSetVar('roles', 'setuserhome',false, 'boolean');
            xarModSetVar('roles', 'setprimaryparent', false, 'boolean');
            xarModSetVar('roles', 'setpasswordupdate',false, 'boolean');
            xarModSetVar('roles', 'setuserlastlogin',false, 'boolean');
            xarModSetVar('roles', 'setusertimezone',false, 'boolean');
            xarModSetVar('roles', 'displayrolelist',false, 'boolean');
            xarModSetVar('roles', 'usereditaccount', true, 'boolean');
            xarModSetVar('roles', 'allowuserhomeedit', false, 'boolean');
            xarModSetVar('roles', 'loginredirect', true, 'boolean');
            xarModSetVar('roles', 'allowexternalurl', false, 'boolean');
            break;
        case '1.1.1':
            xarModSetVar('roles', 'uniqueemail', true, 'boolean');
            $disallowed = xarModGetVar('roles', 'disallowedemails');
            if (!isset($disallowed)) {
                   xarModSetVar('roles','disallowedemails','', 'string'); //let's set it so it doesn't error else leave content to upgrade.php
            }
            break;
        case '1.1.2':
            $lockdata= unserialize(xarModgetVar('roles', 'lockdata'));
            $lockdata['killactive']= false;
            xarModSetVar('roles','lockdata',serialize($lockdata), 'array');
            break;
    }
    // Update successful
    return true;
}

/**
 * Delete the roles module
 *
 * @access public
 * @param none $
 * @return bool false, this module cannot be removed
 * @throws DATABASE_ERROR
 */
function roles_delete()
{
    // this module cannot be removed
    return false;

    /**
     * Drop the tables
     */
    // Get database information
    $dbconn =& xarDBGetConn();
    $tables =& xarDBGetTables();

    $query = xarDBDropTable($tables['roles']);
    if (empty($query)) return; // throw back
    if (!$dbconn->Execute($query)) return;

    $query = xarDBDropTable($tables['rolemembers']);
    if (empty($query)) return; // throw back
    if (!$dbconn->Execute($query)) return;

    /**
     * Remove modvars, instances and masks
     */
    xarModDelAllVars('roles');
    xarRemoveMasks('roles');
    xarRemoveInstances('roles');

    // Deletion successful
    return true;
}

?>